package vip.hello520.util;

import org.apache.commons.codec.DecoderException;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;
/**
 * @author Hello
 */
public class ZkUtils {

    /**
     * 获取一个zk连接,此连接可以操作zk
     *
     * @param zkUrl
     * @param nameSpace
     * @return
     */
    public static CuratorFramework getZkClient(String zkUrl, String nameSpace) {
        //最大重连次数
        int maxRetries = 3;
        //心跳间隔时间
        int sleepTimes = 3000;
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(sleepTimes, maxRetries);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(zkUrl)
                .retryPolicy(retryPolicy)
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(5000)
                .namespace(nameSpace)
                .build();
        client.start();
        return client;
    }

    /**
     * 判断该节点是否存在
     *
     * @param client
     * @param path
     * @return
     * @throws Exception
     */
    public static boolean exists(CuratorFramework client, String path) throws Exception {
        Stat stat = client.checkExists().forPath(path);
        return stat != null;
    }

    /**
     * 解密
     *
     * @param propValue
     * @return
     * @throws DecoderException
     */
    public static String decode(String propValue) throws DecoderException {
        return new String(org.apache.commons.codec.binary.Hex.decodeHex(propValue.toCharArray()));
    }

    /**
     * 加密
     *
     * @param propValue
     * @return
     */
    public static String encode(String propValue) {
        return new String(org.apache.commons.codec.binary.Hex.encodeHex(propValue.getBytes()));
    }
}
